package com.sunwayworld.basemodule.business.utils;

import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriUtils;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpReqUtils {

    private static final Logger log = LoggerFactory.getLogger(HttpReqUtils.class);

    /**
     * POST请求
     * @param url
     * @param objectJson 请求实体类Json
     * @return 响应JSON
     */
    public static String sendPost(String url, String objectJson) throws Exception{
        return sendPost(url,objectJson,null);
    }

    public static String sendPost(String url, String objectJson, Map headers) throws Exception{

        log.info("请求报文：url:[{}],请求参数：[{}]",url,objectJson);
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 超时时间10s,内质检接口返回很慢，暂时设置为10s
//        RequestConfig config =
//                RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
        RequestConfig config =
                RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(config);
        StringEntity entity = new StringEntity(objectJson, "utf-8");
        entity.setContentEncoding("utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type","application/json;charset=utf-8");
        if (headers!=null){
            Set<Map.Entry> entries = headers.entrySet();
            for (Map.Entry entry : entries) {
                httpPost.setHeader(entry.getKey()+"",entry.getValue()+"");
            }
        }
        // 返回结果
        String resBody = null;
        CloseableHttpResponse response = null;
        response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode()!= 200){
            log.error("请求异常，返回码："+response.getStatusLine().getStatusCode());
            log.error("请求异常，返回异常信息为："+response.getStatusLine().getReasonPhrase());
            return null;
        }
        // 获取返回结果
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            resBody = EntityUtils.toString(resEntity);
        }
        log.info("响应报文：url:[{}],返回参数：[{}]",url,resBody);
        EntityUtils.consume(resEntity);
        client.close();
        response.close();
        return resBody;
    }

    /**
     * get请求
     * @param url
     * @param pathParam 请求路径参数
     * @return 响应JSON
     */
    public static String get(String url, String pathParam) throws Exception{
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url + "/" + pathParam);
        // 超时时间10s,内质检接口返回很慢，暂时设置为10s
        RequestConfig config =
                RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
        httpGet.setConfig(config);
        // 返回结果
        String resBody = "";
        CloseableHttpResponse response = null;
        response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode()!= 200){
            log.error("请求异常，返回码："+response.getStatusLine().getStatusCode());
            log.error("请求异常，返回异常信息为："+response.getStatusLine().getReasonPhrase());
            return null;
        }
        // 获取返回结果
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            resBody = EntityUtils.toString(resEntity);
        }
        EntityUtils.consume(resEntity);
        client.close();
        response.close();
        return resBody;
    }

    public static String get(String url, Map params, Map headers)  throws Exception{
        //构造请求参数字符串
        StringBuilder paramsStr = null;
        if (params != null) {
            paramsStr = new StringBuilder();
            Set<Map.Entry> entries = params.entrySet();
            for (Map.Entry entry : entries) {
                String value = (entry.getValue() != null) ? (String.valueOf(entry.getValue())) : "";
                paramsStr.append(entry.getKey() + "=" + URLEncoder.encode(value,"UTF-8") + "&");
            }
            url += "?" + paramsStr.toString();
        }
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        // 超时时间10s,第三方接口不稳定，暂时设置为10s
        RequestConfig config =
                RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
        httpGet.setConfig(config);
        httpGet.setHeader("Accept","application/json");
        httpGet.setHeader("Content-Type","application/json");
        if (headers!=null){
            Set<Map.Entry> entries = headers.entrySet();
            for (Map.Entry entry : entries) {
                httpGet.setHeader(entry.getKey()+"",entry.getValue()+"");
            }
        }

        // 返回结果
        String resBody = null;
        CloseableHttpResponse response = null;
        response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode()!= 200){
            log.error("请求异常，返回码："+response.getStatusLine().getStatusCode());
            log.error("请求异常，返回异常信息为："+response.getStatusLine().getReasonPhrase());
            return null;
        }
        // 获取返回结果
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            resBody = EntityUtils.toString(resEntity);
        }
        EntityUtils.consume(resEntity);
        client.close();
        response.close();
        return resBody;
    }

    /*
     * 是否包含中文
     * */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /*
     * url转换
     * */
    public static String encodedUrl(String oriUrl) {
        if (StringUtils.isBlank(oriUrl)) {
            return "";
        }
        try {
            // 替换空格
            oriUrl = oriUrl.replaceAll("%20", " ");
            // 转码
            oriUrl = UriUtils.encodePath(oriUrl, "UTF-8");
        } catch(Exception e) {
            e.printStackTrace();
            throw new InvalidDataException("文件URL转码异常！");
        }
        return oriUrl;
    }
}
